package com.yj.web.controllers.admin;

import com.yj.web.WeChat.Bean.WxMaterialNews;
import com.yj.web.WeChat.Bean.WxMaterialUploadResult;
import com.yj.web.WeChat.Message.WxXmlMessage;
import com.yj.web.WeChat.Message.WxXmlOutMessage;
import com.yj.web.WeChat.api.WxService;
import com.yj.web.WeChat.service.WxCoreService;
import com.yj.web.model.BaseWebResult;
import com.yj.web.util.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by yanlinyang on 2017/6/2.
 */
@Controller
@RequestMapping("/admin/weixin")
public class WeixinController {
    @Autowired
    private WxService wxService;
    @Autowired
    protected WxCoreService wxcoreService;

    @RequestMapping(value = "/wechatCore", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public void wechatCore(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType("text/html;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);

        String signature = request.getParameter("signature");
        String nonce = request.getParameter("nonce");
        String timestamp = request.getParameter("timestamp");

        if (!wxService.checkSignature(timestamp, nonce, signature)) {
            response.getWriter().println("非法请求");
            return;
        }

        String echostr = request.getParameter("echostr");
        if (StringUtils.isNotBlank(echostr)) {
//            String echoStrOut = String.copyValueOf(echostr.toCharArray());
//            response.getWriter().println(echoStrOut);
            response.getWriter().write(echostr);
            return;
        }

        String encryptType = StringUtils.isBlank(request.getParameter("encrypt_type")) ? "raw" : request.getParameter("encrypt_type");
        if ("raw".equals(encryptType)) {
            // 明文传输的消息
            WxXmlMessage inMessage = WxXmlMessage.fromXml(request.getInputStream());
            WxXmlOutMessage outMessage = this.wxcoreService.route(inMessage);
            if (null != outMessage) {
//                System.out.println(outMessage.toXml());
                String xml = outMessage.toXml().replaceAll("\\s","");
                System.out.println(xml);
                response.getWriter().write(xml);
            }
            return;
        }
        response.getWriter().println("暂时不支持加密请求");
        return;
    }

//    @RequestMapping(value = "getUserInfo")
//    public WxUser getUserInfo(HttpServletResponse response, @RequestParam(value = "openid") String openid, @RequestParam(value = "lang") String lang) {
//        ReturnModel returnModel = new ReturnModel();
//        WxUser wxUser = null;
//        try {
//            wxUser = this.wxService.userInfo(openid, lang);
//            returnModel.setResult(true);
//            returnModel.setDatum(wxUser);
//            renderString(response, returnModel);
//        } catch (WxErrorException e) {
//            returnModel.setResult(false);
//            returnModel.setReason(e.getError().toString());
//            renderString(response, returnModel);
//            logger.error(e.getError().toString());
//        }
//        return wxUser;
//    }

//    public void uploadMaterial(String mediaType, String fileType, String fileName) throws WxErrorException, IOException {
//        InputStream inputStream = ClassLoader.getSystemResourceAsStream(fileName);
//        File tempFile = FileUtils.createTmpFile(inputStream, UUID.randomUUID().toString(), fileType);
//        WxMaterial wxMaterial = new WxMaterial();
//        wxMaterial.setFile(tempFile);
//        wxMaterial.setName(fileName);
//        WxMaterialUploadResult res = wxService.materialFileUpload(mediaType, wxMaterial);
//    }

    /**
     * 上传图片文件
     * @param mediaType image
     * @param fileType jpg
     * @param fileName yinuochoukuan.jpg
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/uploadMaterial", method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody BaseWebResult uploadMaterial(@RequestParam("mediaType") String mediaType, @RequestParam("fileType") String fileType,
                                                      @RequestParam("fileName") String fileName) throws Exception {
        BaseWebResult result = new BaseWebResult();
        WxMaterialUploadResult res = wxService.uploadMaterial(mediaType, fileType, fileName);
        result.setData(res);
        return result;
    }


//    public void addNews() throws WxErrorException {
//        WxMaterialNews wxMpMaterialNewsSingle = new WxMaterialNews();
//        WxMaterialNews.WxMaterialNewsArticle mpMaterialNewsArticleSingle = new WxMaterialNews.WxMaterialNewsArticle();
//        mpMaterialNewsArticleSingle.setAuthor("author");
//        mpMaterialNewsArticleSingle.setThumbMediaId(thumbMediaId);
//        mpMaterialNewsArticleSingle.setTitle("single title");
//        mpMaterialNewsArticleSingle.setContent("single content");
//        mpMaterialNewsArticleSingle.setContentSourceUrl("content url");
//        mpMaterialNewsArticleSingle.setShowCoverPic(true);
//        mpMaterialNewsArticleSingle.setDigest("single news");
//        wxMpMaterialNewsSingle.addArticle(mpMaterialNewsArticleSingle);
//
//        WxMaterialUploadResult resSingle = wxService.materialNewsUpload(wxMpMaterialNewsSingle);
//    }

    @RequestMapping(value = "/addNews", method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody BaseWebResult addNews(@RequestParam("author") String author, @RequestParam("thumbMediaId") String thumbMediaId,
                                               @RequestParam("title") String title, @RequestParam("content") String content,
                                               @RequestParam("contentSourceUrl") String contentSourceUrl, @RequestParam("showCoverPic") boolean showCoverPic,
                                               @RequestParam("digest") String digest) throws Exception {
        BaseWebResult result = new BaseWebResult();
        WxMaterialUploadResult res = wxService.addNews(author, thumbMediaId, title, content, contentSourceUrl, showCoverPic, digest);
        result.setData(res);
        return result;
    }

    @RequestMapping(value = "/getNewsInfo", method = RequestMethod.POST)
    public @ResponseBody BaseWebResult getNewsInfo(@RequestParam("mediaId") String mediaId) throws WxErrorException {
        BaseWebResult result = new BaseWebResult();
//        String singleNewsMediaId = "";
        WxMaterialNews wxMpMaterialNewsSingle = wxService.materialNewsInfo(mediaId);
        result.setData(wxMpMaterialNewsSingle);
        return result;
    }

    @RequestMapping(value = "/getAccessToken", method = RequestMethod.POST)
    public @ResponseBody BaseWebResult getAccessToken() throws WxErrorException {
        BaseWebResult result = new BaseWebResult();
        String accessToken = wxService.getAccessToken(false);
        result.setData(accessToken);
        return result;
    }
}
